<?php

namespace app\admin\controller;


use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-question
 */
class Question extends Backend
{

    protected $model = null;
    protected $year;
    protected $schoolAll;
    public function _initialize()
    {
//        echo "fsdf";exit;
        parent::_initialize();
        $this->model = model('Question');

    }
    public function index(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            print_r($list);exit;
//            echo $this->model->getlastsql();exit;

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add(){
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            $answer = $this->request->post("answer/a");
            if(empty($answer['value'])){
                $this->error("请填写答案！");
            }
            if(empty($answer['ok'])){
                $this->error("请填写正确答案！");
            }

            $okAnswer = false;
            if(!empty($answer['ok'])){
                foreach($answer['ok'] as $k=>$v){
                    if($v == 1){
                        $okAnswer = true;
                    }
                }
            }

            if(!$okAnswer){
                $this->error("请填写正确答案！");
            }

            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['subject_name']=$this->getSubjectName($params['subject']);
                $allAnswer = [];
                $answerOkCount = 0;
                if(count($answer['value']) >= 1){
                    foreach($answer['value'] as $k=>$v){
                        if(empty($v)){
                            continue;
                        }
                        if($answer['ok'][$k] == 1){
                            $answerOkCount++;
                        }
                        $allAnswer[] = $v."###".$answer['ok'][$k];
                    }
                }

                if($params['type'] == 1 && $answerOkCount > 1){
                    $this->error("单选题只能有一个正确答案！");
                }
                if($params['type'] == 3 && $answerOkCount > 1){
                    $this->error("判断题只能有一个正确答案！");
                }
                $params['answer'] = json_encode($allAnswer);

//                print_r($params);exit;
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }



//        $school = Db::name('school')->where(['status'=>1])->select();
        $subject = Db::name('subject')->where(['status'=>1])->select();
//        $cate = Db::name('cate')->where(['status'=>1])->select();
//        print_r($school);exit;
//        $this->assign('yearList', $this->year);
//        $this->assign('shcoolList', $school);
        $this->assign('subjectList', $subject);
//        $this->assign('cateList', $subject);
        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
//        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
//        return parent::edit($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $answer = $this->request->post("answer/a");
//            print_r($answer);exit;
            if(empty($answer['value'])){
                $this->error("请填写答案！");
            }
            if(empty($answer['ok'])){
                $this->error("请填写正确答案！");
            }

            $okAnswer = false;
            if(!empty($answer['ok'])){
                foreach($answer['ok'] as $k=>$v){
                    if($v == 1){
                        $okAnswer = true;
                    }
                }
            }

            if(!$okAnswer){
                $this->error("请填写正确答案！");
            }
            if ($params) {

                $params = $this->preExcludeFields($params);


                $params['subject_name']=$this->getSubjectName($params['subject']);


                $allAnswer = [];
                $answerOkCount = 0;
                if(count($answer['value']) >= 1){
                    foreach($answer['value'] as $k=>$v){
                        if(empty($v)){
                            continue;
                        }
                        if($answer['ok'][$k] == 1){
                            $answerOkCount++;
                        }
                        $allAnswer[] = $v."###".$answer['ok'][$k];
                    }
                }

                if($params['type'] == 1 && $answerOkCount > 1){
                    $this->error("单选题只能有一个正确答案！");
                }
                if($params['type'] == 3 && $answerOkCount > 1){
                    $this->error("判断题只能有一个正确答案！");
                }

                $params['answer'] = json_encode($allAnswer);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
        }


//        $school = Db::name('school')->where(['status'=>1])->select();
//        $schoolOpention = "";
//        if(!empty($school)){
//            foreach($school as $k=>$v){
//                $selected = "";
//                if($v['id'] == $row['school']){
//                    $selected = "selected";
//                }
//                $schoolOpention .="<option value='".$v['id']."' ".$selected.">".$v['name']."</option>";
//            }
//        }
        $subject = Db::name('subject')->where(['status'=>1])->select();
        $subjectOpention = "";
        if(!empty($subject)){
            foreach($subject as $k=>$v){
                $selected = "";
                if($v['id'] == $row['subject']){
                    $selected = "selected";
                }
                $subjectOpention .="<option value='".$v['id']."' ".$selected.">".$v['name']."</option>";
            }
        }

//        $yearOpention = "";
//        if(!empty($this->year)){
//            foreach($this->year as $k=>$v){
//                $selected = "";
//                if($v['val'] == $row['year']){
//                    $yearOpention = "selected";
//                }
//                $yearOpention .="<option value='".$v['val']."' ".$selected.">".$v['name']."</option>";
//            }
//        }
//        $cate = Db::name('cate')->where(['status'=>1])->select();
//        $cateOpention = "";
//        if(!empty($cate)){
//            foreach($cate as $k=>$v){
//                $selected = "";
//                if($v['id'] == $row['cate']){
//                    $selected = "selected";
//                }
//                $cateOpention .="<option value='".$v['id']."' ".$selected.">".$v['title']."</option>";
//            }
//        }

        $answer = "";
        $answerCount = 0;
        if(!empty($row['answer'])){
            $answerArr = json_decode($row['answer'], true);
            if(!empty($answerArr)){
                foreach($answerArr as $k=>$v){
                    $answerCount++;
                    $tempArr = explode("###", $v);
                    if($tempArr[1] == 1){//正确答案
                        $text_str = "正确答案";
                        $text_style = "btn btn-success";
                    } else{
                        $text_str = "选中答案";
                        $text_style = "btn btn-more btn-primary";
                    }
                    $readonly = '';
                    if($row['type'] == 3){
                        $readonly = 'readonly="readonly"';
                    }
                    $answer .= '<div id="div_'.$k.'"><input  class="form-control" name="answer[value][]" id="title_'.$k.'" '.$readonly.' type="text" value="'.$tempArr[0].'" style="margin-top:10px;width:250px;"><span style="margin-left:20px;" id="text_'.$k.'" onclick="dj('.$k.')" class="'.$text_style.'">'.$text_str.'</span><span style="margin-left:20px;" id="del_'.$k.'" onclick="del('.$k.')" class="btn btn-danger">删除</span><input name="answer[ok][]" type="hidden" value="'.$tempArr[1].'" id="answer_'.$k.'" /></div>';
                }
            }

        }

        $answeraddInput = '';
        if($row['type'] == 3){
            $answeraddInput = 'style="display:none"';
        }


//        print_r($school);exit;
        $this->assign('answeraddInput', $answeraddInput);
//        $this->assign('yearOpention', $yearOpention);
//        $this->assign('schoolOpention', $schoolOpention);
        $this->assign('subjectOpention', $subjectOpention);
//        $this->assign('cateOpention',$cateOpention);
        $this->assign('answer', $answer);
        $this->assign('answerCount', $answerCount-1);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    private function getSubjectName($id){
        if(empty($id)){
            return "";
        }

        $rs = Db::name('subject')->where(['id'=>$id])->find();
        if(!empty($rs)){
            return $rs['name'];
        }
        return "";
    }

}
